package com.ruicar.afs.cloud.apply.contract.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.condition.GpsCondition;
import com.ruicar.afs.cloud.apply.contract.service.ApplyContractInfoService;
import com.ruicar.afs.cloud.apply.contract.service.ApplyGpsInfoService;
import com.ruicar.afs.cloud.apply.contract.service.ApplyGpsOrderHistoryService;
import com.ruicar.afs.cloud.apply.contract.service.GpsProductInfoService;
import com.ruicar.afs.cloud.apply.contract.vo.ContractEntryCollectVO;
import com.ruicar.afs.cloud.apply.contract.vo.GpsInstallVO;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCarDetailsService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyChannelInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description: GPS二次派单
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/gps")
public class GpsAgainDistributeController {

    private ApplyCarDetailsService applyCarDetailsService;
    private ApplyOrderInfoService applyOrderInfoService;
    private ApplyGpsOrderHistoryService applyGpsOrderHistoryService;
    private ApplyCostDetailsService applyCostDetailsService;
    private ApplyGpsInfoService applyGpsInfoService;
    private ApplyChannelInfoService applyChannelInfoService;
    private ApplyContractInfoService applyContractInfoService;
    private GpsProductInfoService gpsProductInfoService;
    @PostMapping("/page/info")
    @ApiOperation(value = "获取页面信息")
    public IResponse contractEntryInfo(@RequestParam("applyNo") String applyNo) {

        ApplyCarDetails carDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda()
                .eq(ApplyCarDetails::getApplyNo, applyNo));
        ApplyOrderInfo orderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda()
                .eq(ApplyOrderInfo::getApplyNo, applyNo));
        ApplyChannelInfo applyChannelInfo = applyChannelInfoService.getOne(Wrappers.<ApplyChannelInfo>query().lambda()
                .eq(ApplyChannelInfo::getApplyNo, applyNo));
        orderInfo.setChannelName(applyChannelInfo.getChannelName());
        List<FinCostDetails> costDetails = applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda()
                .eq(FinCostDetails::getApplyNo, applyNo)
                .eq(FinCostDetails::getCostType, ApplyConstants.COST_TYPE_CAR_LOAN));
        ApplyGpsInfo gpsInfo = applyGpsInfoService.getOne(Wrappers.<ApplyGpsInfo>query().lambda()
                .eq(ApplyGpsInfo::getApplyNo, applyNo));
        List<ApplyGpsOrderHistory> gpsOrderHistorys = applyGpsOrderHistoryService.list(Wrappers.<ApplyGpsOrderHistory>query().lambda()
                .eq(ApplyGpsOrderHistory::getApplyNo, applyNo));
        GpsProductInfo gpsProductInfo = gpsProductInfoService.getOne(Wrappers.<GpsProductInfo>query().lambda()
                .lt(GpsProductInfo::getDownTerm, costDetails.get(0).getLoanTerm())
                .ge(GpsProductInfo::getUpTerm, costDetails.get(0).getLoanTerm())
                .eq(GpsProductInfo::getGpsType, gpsInfo.getGpsType())
                .eq(GpsProductInfo::getGpsFirm, gpsInfo.getGpsSupplier()));
        ContractEntryCollectVO vo = new ContractEntryCollectVO();
        vo.setCostDetails(costDetails);
        vo.setGpsFullName(gpsProductInfo.getGpsFullName());
        vo.setOrderInfo(orderInfo != null ? orderInfo : new ApplyOrderInfo());
        vo.setCarDetails(carDetails != null ? carDetails : new ApplyCarDetails());
        vo.setGpsInfo(gpsInfo != null ? gpsInfo : new ApplyGpsInfo());
        vo.setGpsOrderHistorys(gpsOrderHistorys);

        return new IResponse<ContractEntryCollectVO>().setData(vo);
    }

    @Transactional
    @PostMapping("/cancelDistribute")
    @ApiOperation(value = "gps二次派单")
    public IResponse cancelDistribute(@RequestBody ContractEntryCollectVO vo) {
        GpsCondition gpsCondition = new GpsCondition();
        BeanUtils.copyProperties(vo.getGpsInfo(), gpsCondition);
        JSONObject result = applyGpsInfoService.cancelOrderWithVpsInfos(gpsCondition);
        Boolean success = result.getBoolean("Success");
        if (success) {
            return new IResponse().setCode("0000").setMsg("撤销成功");

        } else {
            return new IResponse().setCode("9999").setMsg("撤销失败");
        }

    }

    @Transactional
    @PostMapping("/getAllOrderInfoByAppCode")
    @ApiOperation(value = "获取gps工单信息")
    public IResponse getAllOrderInfoByAppCode(@RequestBody ContractEntryCollectVO vo) {
        GpsCondition gpsCondition = new GpsCondition();
        BeanUtils.copyProperties(vo.getGpsInfo(), gpsCondition);
        JSONObject result = applyGpsInfoService.getAllOrderInfoByAppCode(gpsCondition.getCarId());
        Boolean success = result.getBoolean("Success");
        if (success) {
            return new IResponse().setCode("0000").setData(result.getJSONObject("Data").getJSONObject("orderbaseinfo").getString("OrderStatus"));

        } else {
            return new IResponse().setCode("9999").setMsg("获取工单信息失败");
        }

    }

    @Transactional
    @PostMapping("distribute")
    @ApiOperation(value = "gps二次派单")
    public IResponse distribute(@RequestBody ContractEntryCollectVO vo) {
        //TODO 调用GPS取消派单接口
        GpsCondition gpsCondition = new GpsCondition();
        BeanUtils.copyProperties(vo.getGpsInfo(), gpsCondition);
        GpsInstallVO installVO = applyGpsInfoService.getGpsPreInstallInfo(gpsCondition);
        // 调用GPS派单
        JSONObject result = applyGpsInfoService.updateOrderWithVpsInfos(gpsCondition, installVO);
        Boolean success = result.getBoolean("Success");
        if (success) {
            vo.getGpsInfo().setOrderNo(result.getJSONObject("Data").getString("Id"));
            boolean result1 = applyGpsInfoService.updateById(vo.getGpsInfo());
            ApplyGpsOrderHistory history = new ApplyGpsOrderHistory();
            BeanUtils.copyProperties(vo.getGpsInfo(), history);
            //置空id
            history.setId(null);
            history.setInstallTime(gpsCondition.getPreInstallTime());
            boolean result2 = applyGpsOrderHistoryService.save(history);
            if (result1 && result2) {
                ApplyContractInfo applyContractInfo=applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getApplyNo,gpsCondition.getApplyNo()));
                applyContractInfo.setGpsStatus(ApplyConstants.SEND_TASK);
                applyContractInfoService.updateById(applyContractInfo);
                return new IResponse().setMsg("改派成功");
            } else {
                return new IResponse().setCode("9999").setMsg("派单成功,但数据保存出现错误，请联系业务人员处理");
            }

        } else {
            return new IResponse().setCode("9999").setMsg(result.getString("AllMessages"));
        }

    }

}
